import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */

// 判断是否有权限访问当前路由 
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */

// routes 是所有动态路由 roles是权限
export function filterAsyncRoutes(routes, roles) {
  const res = []
  // 遍历所有动态路由 
  routes.forEach(route => {
    // 把每一个路由用临时变量存储
    const tmp = { ...route }

    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],   //静态路由+可以访问的动态路由
  addRoutes: [] //可以访问的动态路由
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes // 给动态路由重新赋值
    state.routes = constantRoutes.concat(routes) //静态路由和动态路由合并
  }
}

const actions = {
  // 计算生成需要权限访问的动态路由规则
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes 
      if (roles.includes('admin')) { //如果权限包括admin 则获取所有动态路由
        accessedRoutes = asyncRoutes || []
      } else {
        // 如果权限不包含admin 则根据权限筛选除动态路由
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      // 调用SET_ROUTES方法生成动态路由和所有路由
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
